function EU = EU_la(pr,x,delta,alpha,lambda)
% This function calculates the expected utility of a prospect theory individual. It
% incorporates all 3 features of prospect theory.

% pr is a vector of probabilities and x is a (matched) vector of the
% outcomes

match = [pr x];
match = sortrows(match,2); % sort from worst to best outcome

% break into gains and losses
% don't need to include outcome=0 because it's utility is zero
gains = match(match(:,2)>0,:);
losses = match(match(:,2)<0,:);

numg = size(gains,1);
numl = size(losses,1);

% calculate decision weights

if numg > 0
    gaindw = zeros(numg,1);
    gaincum = zeros(numg,1); % cumulative probabilities
    gaincum(numg) = gains(numg,1);
    gaindw(numg) = dw_la(gains(numg,1),delta); % best outcome
    for i=(numg-1):-1:1
        gaincum(i) = gaincum(i+1) + gains(i,1);
        gaindw(i) = dw_la(gaincum(i),delta) - dw_la(gaincum(i+1),delta); 
    end
end

if numl > 0
    lossdw = zeros(numl,1);
    losscum = zeros(numl,1); 
    losscum(1) = losses(1,1);
    lossdw(1) = dw_la(losses(1,1),delta); % worst outcome
    for i=2:numl
        losscum(i) = losscum(i-1) + losses(i,1);
        lossdw(i) = dw_la(losscum(i),delta) - dw_la(losscum(i-1),delta); 
    end
end

if numg > 0
    EUgain = gaindw'*util_la(gains(:,2),lambda,alpha);
else
    EUgain = 0;
end
if numl > 0
    EUloss = lossdw'*util_la(losses(:,2),lambda,alpha);
else
    EUloss = 0;
end
EU = EUgain + EUloss;